{-# LANGUAGE OverloadedStrings, NoMonomorphismRestriction #-}

module Harch where

import Data.Tree
import Data.List
import Data.List.Split
import Text.LaTeX
import Text.LaTeX.Base.Class


-- strip
wschars :: String
wschars = " \t\r\n"

strip :: String -> String
strip = lstrip . rstrip

lstrip :: String -> String
lstrip s = case s of
                  [] -> []
                  (x:xs) -> if elem x wschars
                            then lstrip xs
                            else s

rstrip :: String -> String
rstrip = reverse . lstrip . reverse





-- raw
toForest :: [String] -> [Tree String]
toForest [] = []
toForest (x:xs) = (Node x subForest) : (toForest rest)
    where
        (tree,rest) = span (isPrefixOf " ") xs
        subForest = toForest $ map (drop 4) tree

-- (name, desc)
toDescForest :: [Tree String] -> [Tree (String,String)]
toDescForest = fmap $ fmap (splitt)
    where
        splitl = splitOn ": "
        splitt = (\x -> (x!!0,x!!1)).splitl

-- Elem
data Elem = Elem {
    name :: String,
    parent :: String,
    leafs :: String,
    desc :: String}
    deriving (Show, Eq, Ord)

toElemForest :: [Tree (String,String)] -> [Tree Elem]
toElemForest = toElemForest' "None"

toElemForest' :: String -> [Tree (String,String)] -> [Tree Elem]
toElemForest' par = map go 
    where
        go (Node (a,b) sub) = Node (Elem a par (pretty $ rake sub) b) (toElemForest' a sub)
        rake = (intercalate ", " ) . (map (fst . rootLabel))
        pretty s = case s of
            "" -> "None"
            ok -> ok

toElemList :: [Tree Elem] -> [Elem]
toElemList = concat . map flatten
